package main

import (
	"go.bug.st/serial"
	"log"
	"time"
)

func getRs232Data() {
	mode := &serial.Mode{
		BaudRate: 9600,
		DataBits: 8,
		StopBits: serial.OneStopBit,
	}

	port, err := serial.Open(portName, mode)
	if err != nil {
		log.Println("串口连接失败: %v", err)
		panic(err)
	}
	log.Println("串口连接成功")
	defer port.Close()
	log.Println("开始获取数据")

	err = port.ResetInputBuffer()
	err = port.ResetOutputBuffer()
	if err != nil {
		log.Printf("重置缓冲区失败:%v", err)
	}

	// 读取数据
	buf := make([]byte, 256)
	for {
		n, err := port.Read(buf)
		if err != nil {
			dataChannel <- []byte("")
			// 稍微等待，避免过快地发送数据
			time.Sleep(1000 * time.Millisecond)
			log.Printf("串口数据读取失败，请检查串口线连接后重启该软件: %v", err)
			continue
		}
		if n == 0 {
			dataChannel <- []byte("")
			// 稍微等待，避免过快地发送数据
			time.Sleep(1000 * time.Millisecond)
			log.Printf("没有数据")
			continue
		}

		// 打印读取到的数据
		log.Printf("Received %d bytes: %v\n", n, buf[:n])
		log.Printf("Received %d string: %v\n", n, string(buf[:n]))

		dataChannel <- buf[6:14]
		// 稍微等待，避免过快地发送数据
		time.Sleep(100 * time.Millisecond)
	}

}
